import os
import re
import xml.etree.ElementTree as ET
from copy import deepcopy

# 定义输入和输出目录
php_base_dir = 'D:\\Projects\\front\\lang'
xml_base_dir = 'D:\\Projects\\oraimo-android\\business_affiliate\\src\\main\\res\\values'
xml_base_dir2 = 'D:\\Projects\\oraimo-android\\business_affiliate\\src\\main\\res'
languages = ['ar', 'bn', 'fr', 'pt', 'zh_CN']

def parse_php_array(content):
    """递归解析PHP数组内容"""
    def parse_array(array_content):
        array_dict = {}
        matches = re.findall(r"'([^']+)'\s*=>\s*'([^']+)'", array_content, re.DOTALL)
        for match in matches:
            key, value = match
            array_dict[key.lower()] = value

        matches = re.findall(r'"([^"]+)"\s*=>\s*"([^"]+)"', array_content, re.DOTALL)
        for match in matches:
            key, value = match
            array_dict[key.lower()] = value
        return array_dict

    return parse_array(content)

def parse_php_file(file_path):
    """从PHP文件中解析key-value对"""
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    # 去掉开头和结尾的<?php return [ 和 ]; 部分
    content = re.sub(r"^\s*<\?php\s*return\s*\[", "", content)
    content = re.sub(r"\];\s*$", "", content)
    return parse_php_array(content)

def read_xml_template(file_path):
    """读取现有的strings.xml文件作为模板"""
    tree = ET.parse(file_path)
    return tree

def generate_strings_xml(lang_dir, output_dir, template_tree):
    """生成新的strings.xml文件"""
    for lang in languages:
        php_files = [os.path.join(lang_dir, lang, file) for file in os.listdir(os.path.join(lang_dir, lang)) if file.endswith('.php')]
        translations = {}
        for php_file in php_files:
            translations.update(parse_php_file(php_file))

        # 输出解析的键值对用于调试
        print(f"Translations for {lang}: {translations}")

        # 复制模板树
        new_tree = deepcopy(template_tree)
        root = new_tree.getroot()

        # 更新值
        for string in root.findall('string'):
            value = string.text.lower()  # 获取当前的值并转换为小写
            if value in translations:
                string.text = translations[value]

        # 创建新的语言目录并保存文件
        output_lang_dir = os.path.join(output_dir, f'values-{lang.replace("_", "-")}')
        os.makedirs(output_lang_dir, exist_ok=True)
        new_tree.write(os.path.join(output_lang_dir, 'strings.xml'), encoding='utf-8', xml_declaration=True)
        print(f"Generated strings.xml for {lang} at {output_lang_dir}")

if __name__ == "__main__":
    template_file = os.path.join(xml_base_dir, 'strings.xml')
    xml_template_tree = read_xml_template(template_file)
    generate_strings_xml(php_base_dir, xml_base_dir2, xml_template_tree)
